package com.jmlee.interceptor;

import com.jmlee.component.HostHolder;
import com.jmlee.pojo.Admin;
import com.jmlee.pojo.LoginTicket;
import com.jmlee.service.AdminService;
import com.jmlee.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @Description 用户信息登录验证
 * @Author jmLee
 * @Date 2021/3/4 14:21
 * @Version 1.0
 */
@Component("LoginTicketInterceptor")
public class LoginTicketInterceptor implements HandlerInterceptor {


    @Autowired
    private AdminService adminService;

    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从cookie中获取凭证
        String ticket = CookieUtil.getCookieValue(request, "ticket");

        if (ticket != null) {
            // 去数据库查询用户登录凭证(现已改成去Redis中查找凭证，不去数据库查找了)
            LoginTicket loginTicket = adminService.findLoginTicket(ticket);

            // 检查凭证是否有效
            if (loginTicket != null && loginTicket.getExpired().after(new Date())) {

                // 根据登录凭证查询用户
                Admin admin = adminService.findAdminById(loginTicket.getUserId());

                // 在本次请求中持有用户（代替session存储user对象）
                hostHolder.setAdmin(admin);

                // 如果用户登录时间还未过期，则直接放行，进入后台首页
                return true;
            }
        }

        response.sendRedirect("/");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        Admin admin = hostHolder.getAdmin();
        if (admin != null && modelAndView != null) {
            modelAndView.addObject("loginAdmin",admin);
        }
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 手动清空ThreadLocal内部数据，防止内存泄露
        hostHolder.clear();
    }
}
